package cn.harry.cabinet.service

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import cn.harry.cabinet.R

/**
 * 定时重启前台服务
 * 保持应用在后台运行，确保定时任务能够正常执行
 */
class AutoRestartService : Service() {

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    /**
     * 创建通知渠道（Android 8.0+需要）
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "定时重启服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "保持定时重启功能运行"
                setShowBadge(false)
            }

            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建通知
     */
    private fun createNotification() = NotificationCompat.Builder(this, CHANNEL_ID)
        .setContentTitle("定时重启已启用")
        .setContentText("应用将在设定时间自动重启")
        .setSmallIcon(R.drawable.ic_settings)
        .setPriority(NotificationCompat.PRIORITY_LOW)
        .setOngoing(true)
        .build()

    companion object {
        private const val NOTIFICATION_ID = 10086
        private const val CHANNEL_ID = "auto_restart_service"

        /**
         * 启动服务
         */
        fun startService(context: Context) {
            val intent = Intent(context, AutoRestartService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }

        /**
         * 停止服务
         */
        fun stopService(context: Context) {
            val intent = Intent(context, AutoRestartService::class.java)
            context.stopService(intent)
        }
    }
}
